import { NextRequest, NextResponse } from 'next/server';
import { readCategories, writeCategories, readWords, writeWords, generateId, initDataFiles, initDefaultCategories } from '@/lib/data';
import { Category, Word } from '@/types';

// 初始化完整的数据结构
export async function POST(request: NextRequest) {
  try {
    initDataFiles();
    initDefaultCategories();

    // 检查是否已经有数据
    const existingCategories = readCategories();
    const existingWords = readWords();
    
    if (existingCategories.length > 6 || existingWords.length > 0) {
      return NextResponse.json({
        success: false,
        message: '数据已存在，请先清空数据再初始化',
      }, { status: 400 });
    }

    const categories: Category[] = [];
    const words: Word[] = [];

    // 小学1-6年级
    const primaryGrades = ['一年级', '二年级', '三年级', '四年级', '五年级', '六年级'];
    primaryGrades.forEach((gradeName, gradeIndex) => {
      const gradeId = `primary-grade${gradeIndex + 1}`;
      const gradeCategory: Category = {
        id: gradeId,
        name: gradeName,
        parentId: 'primary',
        path: `小学/${gradeName}`,
        level: 2,
      };
      categories.push(gradeCategory);

      // 上下学期
      const semesters = ['上学期', '下学期'];
      semesters.forEach((semesterName, semesterIndex) => {
        const semesterId = `${gradeId}-semester${semesterIndex + 1}`;
        const semesterCategory: Category = {
          id: semesterId,
          name: semesterName,
          parentId: gradeId,
          path: `小学/${gradeName}/${semesterName}`,
          level: 3,
        };
        categories.push(semesterCategory);

        // 6个单元
        for (let unitIndex = 1; unitIndex <= 6; unitIndex++) {
          const unitId = `${semesterId}-unit${unitIndex}`;
          const unitCategory: Category = {
            id: unitId,
            name: `单元${unitIndex}`,
            parentId: semesterId,
            path: `小学/${gradeName}/${semesterName}/单元${unitIndex}`,
            level: 4,
          };
          categories.push(unitCategory);

          // 每个单元添加10个单词
          const unitWords = generateWordsForUnit(unitId, unitIndex, gradeIndex + 1, 'primary');
          words.push(...unitWords);
        }
      });
    });

    // 初中1-3年级
    const middleGrades = ['一年级', '二年级', '三年级'];
    middleGrades.forEach((gradeName, gradeIndex) => {
      const gradeId = `middle-grade${gradeIndex + 1}`;
      const gradeCategory: Category = {
        id: gradeId,
        name: gradeName,
        parentId: 'middle',
        path: `初中/${gradeName}`,
        level: 2,
      };
      categories.push(gradeCategory);

      // 上下学期
      const semesters = ['上学期', '下学期'];
      semesters.forEach((semesterName, semesterIndex) => {
        const semesterId = `${gradeId}-semester${semesterIndex + 1}`;
        const semesterCategory: Category = {
          id: semesterId,
          name: semesterName,
          parentId: gradeId,
          path: `初中/${gradeName}/${semesterName}`,
          level: 3,
        };
        categories.push(semesterCategory);

        // 6个单元
        for (let unitIndex = 1; unitIndex <= 6; unitIndex++) {
          const unitId = `${semesterId}-unit${unitIndex}`;
          const unitCategory: Category = {
            id: unitId,
            name: `单元${unitIndex}`,
            parentId: semesterId,
            path: `初中/${gradeName}/${semesterName}/单元${unitIndex}`,
            level: 4,
          };
          categories.push(unitCategory);

          // 每个单元添加10个单词
          const unitWords = generateWordsForUnit(unitId, unitIndex, gradeIndex + 1, 'middle');
          words.push(...unitWords);
        }
      });
    });

    // 高中1-3年级
    const highGrades = ['一年级', '二年级', '三年级'];
    highGrades.forEach((gradeName, gradeIndex) => {
      const gradeId = `high-grade${gradeIndex + 1}`;
      const gradeCategory: Category = {
        id: gradeId,
        name: gradeName,
        parentId: 'high',
        path: `高中/${gradeName}`,
        level: 2,
      };
      categories.push(gradeCategory);

      // 上下学期
      const semesters = ['上学期', '下学期'];
      semesters.forEach((semesterName, semesterIndex) => {
        const semesterId = `${gradeId}-semester${semesterIndex + 1}`;
        const semesterCategory: Category = {
          id: semesterId,
          name: semesterName,
          parentId: gradeId,
          path: `高中/${gradeName}/${semesterName}`,
          level: 3,
        };
        categories.push(semesterCategory);

        // 6个单元
        for (let unitIndex = 1; unitIndex <= 6; unitIndex++) {
          const unitId = `${semesterId}-unit${unitIndex}`;
          const unitCategory: Category = {
            id: unitId,
            name: `单元${unitIndex}`,
            parentId: semesterId,
            path: `高中/${gradeName}/${semesterName}/单元${unitIndex}`,
            level: 4,
          };
          categories.push(unitCategory);

          // 每个单元添加10个单词
          const unitWords = generateWordsForUnit(unitId, unitIndex, gradeIndex + 1, 'high');
          words.push(...unitWords);
        }
      });
    });

    // 四级和六级
    const cetLevels = [
      { id: 'cet4', name: '四级', parentId: 'college' },
      { id: 'cet6', name: '六级', parentId: 'college' },
    ];

    cetLevels.forEach((cetLevel) => {
      // 6个单元
      for (let unitIndex = 1; unitIndex <= 6; unitIndex++) {
        const unitId = `${cetLevel.id}-unit${unitIndex}`;
        const unitCategory: Category = {
          id: unitId,
          name: `单元${unitIndex}`,
          parentId: cetLevel.id,
          path: `大学/${cetLevel.name}/单元${unitIndex}`,
          level: 3,
        };
        categories.push(unitCategory);

        // 每个单元添加10个单词
        const unitWords = generateWordsForUnit(unitId, unitIndex, cetLevel.id === 'cet4' ? 4 : 6, 'cet');
        words.push(...unitWords);
      }
    });

    // 保存所有分类和单词
    const allCategories = [...existingCategories, ...categories];
    writeCategories(allCategories);
    writeWords(words);

    return NextResponse.json({
      success: true,
      message: '数据初始化成功',
      stats: {
        categoriesCreated: categories.length,
        wordsCreated: words.length,
      },
    });
  } catch (error: any) {
    return NextResponse.json({
      success: false,
      message: '初始化失败',
      error: error.message,
    }, { status: 500 });
  }
}

// 生成单词的函数
function generateWordsForUnit(unitId: string, unitIndex: number, level: number, type: 'primary' | 'middle' | 'high' | 'cet'): Word[] {
  const words: Word[] = [];
  const wordList = getWordList(type, level, unitIndex);
  
  wordList.forEach((wordPair) => {
    const word: Word = {
      id: generateId(),
      english: wordPair.english,
      chinese: wordPair.chinese,
      categoryId: unitId,
      createdAt: new Date().toISOString(),
    };
    words.push(word);
  });

  return words;
}

// 获取单词列表
function getWordList(type: 'primary' | 'middle' | 'high' | 'cet', level: number, unitIndex: number): Array<{ english: string; chinese: string }> {
  // 预定义的单词库（每个单元10个单词）
  const wordBanks = {
    primary: [
      ['apple', '苹果'], ['book', '书'], ['cat', '猫'], ['dog', '狗'], ['egg', '鸡蛋'],
      ['fish', '鱼'], ['girl', '女孩'], ['hat', '帽子'], ['ice', '冰'], ['jump', '跳'],
      ['kite', '风筝'], ['lion', '狮子'], ['moon', '月亮'], ['nose', '鼻子'], ['orange', '橙子'],
      ['pen', '钢笔'], ['queen', '女王'], ['red', '红色'], ['sun', '太阳'], ['tree', '树'],
      ['umbrella', '雨伞'], ['violin', '小提琴'], ['water', '水'], ['yellow', '黄色'], ['zoo', '动物园'],
      ['bird', '鸟'], ['car', '汽车'], ['door', '门'], ['eye', '眼睛'], ['friend', '朋友'],
      ['green', '绿色'], ['house', '房子'], ['jacket', '夹克'], ['key', '钥匙'], ['lamp', '灯'],
      ['map', '地图'], ['pencil', '铅笔'], ['question', '问题'], ['rabbit', '兔子'], ['school', '学校'],
      ['table', '桌子'], ['vegetable', '蔬菜'], ['window', '窗户'], ['zebra', '斑马'], ['airplane', '飞机'],
      ['balloon', '气球'], ['computer', '电脑'], ['dinosaur', '恐龙'], ['elephant', '大象'], ['flower', '花'],
      ['guitar', '吉他'], ['helicopter', '直升机'], ['island', '岛屿'], ['banana', '香蕉'], ['chair', '椅子'],
      ['desk', '桌子'], ['frog', '青蛙'], ['garden', '花园'], ['horse', '马'], ['insect', '昆虫'],
      ['juice', '果汁'], ['kangaroo', '袋鼠'], ['library', '图书馆'], ['mountain', '山'], ['newspaper', '报纸'],
      ['ocean', '海洋'], ['piano', '钢琴'], ['quilt', '被子'], ['river', '河流'], ['stairs', '楼梯'],
      ['teacher', '老师'], ['uniform', '制服'], ['vacation', '假期'], ['winter', '冬天'], ['airport', '机场'],
      ['bridge', '桥'], ['castle', '城堡'], ['dolphin', '海豚'], ['engine', '引擎'], ['family', '家庭'],
      ['giraffe', '长颈鹿'], ['hospital', '医院'], ['jungle', '丛林'], ['kitchen', '厨房'], ['lighthouse', '灯塔'],
    ],
    middle: [
      ['achieve', '达到，完成'], ['beautiful', '美丽的'], ['challenge', '挑战'], ['develop', '发展'], ['education', '教育'],
      ['fantastic', '极好的'], ['government', '政府'], ['important', '重要的'], ['journey', '旅程'], ['knowledge', '知识'],
      ['language', '语言'], ['medicine', '药物'], ['necessary', '必要的'], ['opportunity', '机会'], ['practice', '练习'],
      ['quality', '质量'], ['research', '研究'], ['society', '社会'], ['technology', '技术'], ['university', '大学'],
      ['wonderful', '精彩的'], ['excellent', '优秀的'], ['ability', '能力'], ['balance', '平衡'], ['dangerous', '危险的'],
      ['exercise', '锻炼'], ['foreign', '外国的'], ['generous', '慷慨的'], ['imagine', '想象'], ['limited', '有限的'],
      ['manage', '管理'], ['obvious', '明显的'], ['rapid', '快速的'], ['serious', '严肃的'], ['traffic', '交通'],
      ['urgent', '紧急的'], ['various', '各种各样的'], ['welcome', '欢迎'], ['careful', '仔细的'], ['famous', '著名的'],
      ['general', '一般的'], ['honest', '诚实的'], ['improve', '改善'], ['nature', '自然'], ['observe', '观察'],
      ['perfect', '完美的'], ['rapid', '快速的'], ['serious', '严肃的'], ['traffic', '交通'], ['urgent', '紧急的'],
      ['various', '各种各样的'], ['welcome', '欢迎'], ['xenial', '好客的'], ['youthful', '年轻的'], ['zealous', '热心的'],
      ['benefit', '利益'], ['careful', '仔细的'], ['develop', '发展'], ['educate', '教育'], ['famous', '著名的'],
      ['general', '一般的'], ['honest', '诚实的'], ['improve', '改善'], ['journey', '旅程'], ['knowledge', '知识'],
    ],
    high: [
      ['accomplish', '完成'], ['beneficial', '有益的'], ['complicated', '复杂的'], ['democracy', '民主'], ['enthusiasm', '热情'],
      ['fundamental', '基础的'], ['guarantee', '保证'], ['hypothesis', '假设'], ['independent', '独立的'], ['justification', '理由'],
      ['knowledgeable', '博学的'], ['laboratory', '实验室'], ['magnificent', '壮丽的'], ['negotiation', '谈判'], ['opportunity', '机会'],
      ['perspective', '观点'], ['qualification', '资格'], ['recommendation', '推荐'], ['sophisticated', '复杂的'], ['tremendous', '巨大的'],
      ['unanimous', '一致的'], ['versatile', '多才多艺的'], ['wonderful', '精彩的'], ['xenophobia', '仇外心理'], ['youthful', '年轻的'],
      ['zealous', '热心的'], ['academic', '学术的'], ['boundary', '边界'], ['contemporary', '当代的'], ['dimension', '维度'],
      ['elaborate', '详细的'], ['facilitate', '促进'], ['guarantee', '保证'], ['hypothesis', '假设'], ['illustrate', '说明'],
      ['justify', '证明'], ['knowledgeable', '博学的'], ['laboratory', '实验室'], ['magnificent', '壮丽的'], ['negotiate', '谈判'],
      ['observe', '观察'], ['perspective', '观点'], ['qualify', '使合格'], ['recommend', '推荐'], ['sophisticate', '使复杂化'],
      ['tremendous', '巨大的'], ['unanimous', '一致的'], ['versatile', '多才多艺的'], ['wonderful', '精彩的'], ['xenophobia', '仇外心理'],
      ['youthful', '年轻的'], ['zealous', '热心的'], ['academic', '学术的'], ['boundary', '边界'], ['contemporary', '当代的'],
      ['dimension', '维度'], ['elaborate', '详细的'], ['facilitate', '促进'], ['guarantee', '保证'], ['hypothesis', '假设'],
    ],
    cet: [
      // 四级
      ['abandon', '放弃'], ['absolute', '绝对的'], ['academic', '学术的'], ['accomplish', '完成'], ['accurate', '准确的'],
      ['achieve', '达到'], ['acknowledge', '承认'], ['acquire', '获得'], ['adapt', '适应'], ['adequate', '足够的'],
      ['adjust', '调整'], ['administration', '管理'], ['adopt', '采用'], ['advance', '前进'], ['advantage', '优势'],
      ['advocate', '提倡'], ['affect', '影响'], ['afford', '负担得起'], ['agency', '机构'], ['agenda', '议程'],
      ['aggressive', '侵略性的'], ['aid', '援助'], ['alarm', '警报'], ['alert', '警觉的'], ['alien', '外国的'],
      ['allege', '声称'], ['allocate', '分配'], ['allow', '允许'], ['alter', '改变'], ['alternative', '替代的'],
      ['amateur', '业余的'], ['amaze', '使惊讶'], ['ambassador', '大使'], ['ambiguous', '模糊的'], ['ambition', '雄心'],
      ['amend', '修改'], ['amount', '数量'], ['amplify', '放大'], ['amuse', '逗乐'], ['analyze', '分析'],
      ['ancestor', '祖先'], ['anchor', '锚'], ['ancient', '古代的'], ['anger', '愤怒'], ['angle', '角度'],
      ['announce', '宣布'], ['annual', '每年的'], ['anonymous', '匿名的'], ['anticipate', '预期'], ['anxiety', '焦虑'],
      // 六级
      ['abbreviation', '缩写'], ['abide', '遵守'], ['abolish', '废除'], ['abrupt', '突然的'], ['absence', '缺席'],
      ['absolute', '绝对的'], ['absorb', '吸收'], ['abstract', '抽象的'], ['absurd', '荒谬的'], ['abundance', '丰富'],
      ['academic', '学术的'], ['accelerate', '加速'], ['accent', '口音'], ['accept', '接受'], ['access', '访问'],
      ['accommodate', '容纳'], ['accompany', '陪伴'], ['accomplish', '完成'], ['accord', '一致'], ['account', '账户'],
      ['accumulate', '积累'], ['accurate', '准确的'], ['accuse', '指控'], ['accustom', '使习惯'], ['achieve', '达到'],
      ['acknowledge', '承认'], ['acquaint', '使熟悉'], ['acquire', '获得'], ['activate', '激活'], ['actual', '实际的'],
      ['acute', '尖锐的'], ['adapt', '适应'], ['addict', '上瘾者'], ['addition', '添加'], ['adequate', '足够的'],
      ['adhere', '坚持'], ['adjacent', '邻近的'], ['adjust', '调整'], ['administer', '管理'], ['admire', '钦佩'],
      ['admission', '承认'], ['adolescent', '青少年'], ['adopt', '采用'], ['adore', '崇拜'], ['advance', '前进'],
      ['advantage', '优势'], ['adventure', '冒险'], ['adverse', '不利的'], ['advertise', '做广告'], ['advocate', '提倡'],
      ['aesthetic', '美学的'], ['affect', '影响'], ['affiliate', '附属'], ['affirm', '肯定'], ['afflict', '折磨'],
      ['afford', '负担得起'], ['agenda', '议程'], ['agent', '代理人'], ['aggravate', '加重'], ['aggregate', '总计'],
    ],
  };

  // 根据类型选择单词库
  let bank: string[][] = [];
  if (type === 'primary') {
    bank = wordBanks.primary;
  } else if (type === 'middle') {
    bank = wordBanks.middle;
  } else if (type === 'high') {
    bank = wordBanks.high;
  } else if (type === 'cet') {
    bank = wordBanks.cet;
  }

  // 根据单元索引选择10个单词（循环使用）
  const startIndex = ((unitIndex - 1) * 10) % bank.length;
  const selectedWords: Array<{ english: string; chinese: string }> = [];
  
  for (let i = 0; i < 10; i++) {
    const index = (startIndex + i) % bank.length;
    selectedWords.push({
      english: bank[index][0],
      chinese: bank[index][1],
    });
  }

  return selectedWords;
}
